import {
  GetPlaceListForPage,
  postItineraryEditForUser,
  getItineraryCatalogListAllForComboBox
} from '../../api/home'
import {
  imageURL
} from '../../../utils/request'

Page({
  data: {
    imageURL: '',
    calendarConfig: {
      chooseAreaMode: true // 開啟範圍選擇模式
    },

    showPopup: false,
    activeTab: 'date', // 默認打開天數 tab
    dayOptions: Array.from({
      length: 30
    }, (_, i) => i + 1),
    selectedDayIndex: 0,
    preferences: [],
    //交通選擇
    transportOptions: [{
        label: '公共交通',
        icon: '/pages/assets/image/bus.svg',
        transportation: 1
      },
      {
        label: '駕車',
        icon: '/pages/assets/image/car.svg',
        transportation: 2
      },
      {
        label: '走路',
        icon: '/pages/assets/image/go.svg',
        transportation: 3
      }
    ],
    selectedTransportIndex: 0, // 默認選中第一個
    cardList: [],
    //時間選擇
    hours: Array.from({
      length: 24
    }, (_, i) => (i < 10 ? '0' + i : '' + i)),
    minutes: Array.from({
      length: 60
    }, (_, i) => (i < 10 ? '0' + i : '' + i)),
    startTime: ['08', '00'],
    endTime: ['20', '00'],
    showModal: false,
    days: [],
    diffDays: '',
    daysIndex: 0,
    itineraryPayload: {
      itinerary_id: '',
      number_day: '',
      itinerary_catalog_id: 1,
      name: '',
      transportation: 1,
      start_time: '',
      end_time: '',
      img_url_cover: '',
      list_item: [] // 每次 toggleSelect 后更新
    },
    allChildren: [],
    currentSelectedPlace: null,
  },
  onLoad() {
    wx.removeStorageSync('start_time')
    wx.removeStorageSync('end_time')
    wx.removeStorageSync('payload')

    this.setData({
      imageURL
    })
    this.getHotList()
    this.getPlayLike()
  },
  onShow() {
    console.log(111111);
    const payload = wx.getStorageSync('payload')
    const start_time = wx.getStorageSync('start_time')
    const end_time = wx.getStorageSync('end_time')
    if (payload.itinerary_catalog_id) {
      const allChildren = payload.list_item.flatMap(d => d.child)
      console.log(allChildren);
      this.setData({
        itineraryPayload: payload,
        allChildren,
      })
      console.log(payload);
    }
    if (start_time) {
      this.setData({
        'itineraryPayload.start_time': start_time,
        'itineraryPayload.end_time': end_time,
      })
    }
    // ✅ 勾选推荐列表中已有的景点
    if (this.data.cardList.length > 0 && payload.list_item) {
      // ✅ 拿出所有已选 place_id
      const selectedIds = (payload.list_item || []).flatMap(d =>
        d.child.map(c => c.place_id)
      )

      // ✅ 更新推荐列表 cardList，把已选的标记成 selected = true
      const newCardList = this.data.cardList.map(item => ({
        ...item,
        selected: selectedIds.includes(item.place_id)
      }))

      this.setData({
        cardList: newCardList
      })
      console.log(newCardList);
    }
  },
  async getPlayLike() {
    const res = await getItineraryCatalogListAllForComboBox()
    this.setData({
      preferences: res.data.list
    })
  },
  async getHotList() {
    const res = await GetPlaceListForPage({
      // is_hot:1
    })
    const list = (res.data.list || []).map(item => {
      return {
        ...item,
        selected: false // 默认都加上 selected
      }
    })

    this.setData({
      cardList: list
    })
  },
  // 输入事件
  onInputChange(e) {
    this.setData({
      'itineraryPayload.name': e.detail.value
    });
  },
  openModal() {
    this.setData({
      showModal: true
    });
  },

  closeModal() {
    this.setData({
      showModal: false
    });
  },
  removePlaceFromList(place_id) {
    let payload = this.data.itineraryPayload
  
    // 遍历每一天，删除对应的景点
    payload.list_item.forEach(dayItem => {
      if (dayItem.child && dayItem.child.length) {
        dayItem.child = dayItem.child.filter(c => c.place_id !== place_id)
      }
    })
  
    // ❌ 不要直接把空 day 删除，否则会把整个 allChildren 清空
    // payload.list_item = payload.list_item.filter(dayItem => dayItem.child.length > 0)
  
    // 🔑 删除后重新合并 allChildren
    const allChildren = payload.list_item.flatMap(d => d.child || [])
  
    this.setData({
      itineraryPayload: payload,
      allChildren
    })
  
    console.log('刪除後 payload:', payload)
    console.log('刪除後合併的 allChildren:', allChildren)
  },  


  // confirmSelect() {
  //   const place = this.data.currentSelectedPlace
  //   const day_num = this.data.selectedDayIndex + 1 // DAY 1 -> 1

  //   if (!place) {
  //     wx.showToast({
  //       title: '未選擇地點',
  //       icon: 'none'
  //     })
  //     return
  //   }

  //   let payload = this.data.itineraryPayload

  //   // 如果还没设置封面图，用第一个 place 的图
  //   if (!payload.img_url_cover) {
  //     payload.img_url_cover = place.img_url_cover || ''
  //   }

  //   // 查找对应 day_num
  //   let dayItem = payload.list_item.find(d => d.day_num === day_num)
  //   if (!dayItem) {
  //     dayItem = {
  //       theme: '',
  //       day_num,
  //       child: []
  //     }
  //     payload.list_item.push(dayItem)
  //   }

  //   // 确认是否已经存在
  //   const exists = dayItem.child.some(c => c.place_id === place.place_id)
  //   if (!exists) {
  //     dayItem.child.push({
  //       place_id: place.place_id,
  //       title: place.name,
  //       type: 11,
  //       start_time: '',
  //       end_time: '',
  //       img_url_cover: place.img_url_cover || ''
  //     })
  //   }

  //   this.setData({
  //     itineraryPayload: payload,
  //     showModal: false,
  //     selectedDayIndex: 0,
  //     currentSelectedPlace: null
  //   })

  //   console.log('当前拼装的 payload:', this.data.itineraryPayload)
  // },

  // 切換選擇狀態
toggleSelect(e) {
  const start_time = wx.getStorageSync('start_time')
  const end_time = wx.getStorageSync('end_time')
  if (!start_time || !end_time) {
    wx.showToast({
      title: '請先選擇日期',
      icon: 'none'
    })
    return
  }

  const id = e.currentTarget.dataset.id
  let selectedItem = null

  const newList = this.data.allChildren.map(item => {
    if (item.place_id === id) {
      const newSelected = !item.selected // 点击后新的状态
      const updated = { ...item, selected: newSelected }
      selectedItem = updated
      return updated
    }
    return item
  })

  this.setData({ allChildren: newList })

  if (!selectedItem) return

  if (selectedItem.selected) {
    // ✅ 只有从 false → true 才弹框
    this.setData({
      currentSelectedPlace: selectedItem
    })
    this.openModal()
  } else {
    // ✅ true → false 的时候，删除行程里的记录
    this.removePlaceFromList(selectedItem.place_id)
  }
},
  

  // 确认选择DAY
  confirmSelect() {
    const place = this.data.currentSelectedPlace
    const day_num = this.data.selectedDayIndex + 1

    if (!place) {
      wx.showToast({ title: '未選擇地點', icon: 'none' })
      return
    }

    let payload = this.data.itineraryPayload


    // 初始化封面
    if (!payload.img_url_cover) {
      payload.img_url_cover = place.img_url_cover || ''
    }

    // 查找当天
    let dayItem = payload.list_item.find(d => d.day_num === day_num)
    if (!dayItem) {
      dayItem = { theme: '', day_num, child: [] }
      payload.list_item.push(dayItem)
    }

    // 检查是否已存在
    const exists = dayItem.child.some(c => c.place_id === place.place_id)

    if (!exists) {
      dayItem.child.push({
        place_id: place.place_id,
        title: place.name,
        type: 11,
        start_time: '',
        end_time: '',

        img_url_cover: place.img_url_cover || ''
      })
    }

    // ✅ 关键：保证 list_item 始终按 day_num 升序
    payload.list_item.sort((a, b) => a.day_num - b.day_num)
    const allChildren = payload.list_item.flatMap(d => d.child)

    this.setData({
      itineraryPayload: payload,
      allChildren,
      showModal: false,
      currentSelectedPlace: null,
      selectedDayIndex:0
    })

    console.log('当前拼装的 payload:', this.data.itineraryPayload)
    wx.setStorageSync('payload', payload)
  },



  handleButtonClick() {
    wx.showToast({
      title: '按鈕被點擊',
      icon: 'none'
    })
  },
  onSelectTransport(e) {
    const index = e.currentTarget.dataset.index;
    const transportation = e.currentTarget.dataset.id;

    this.setData({
      selectedTransportIndex: index,
      transportation
    });
  },
  togglePreference(e) {
    const itinerary_catalog_id = e.currentTarget.dataset.id;
    this.setData({
      'itineraryPayload.itinerary_catalog_id': itinerary_catalog_id
    });
  },

  onStartTimeChange(e) {
    const hour = this.data.hours[e.detail.value[0]];
    const minute = this.data.minutes[e.detail.value[1]];
    this.setData({
      startTime: [hour, minute]
    });
    console.log('開始時間：', hour + ':' + minute);
  },

  onEndTimeChange(e) {
    const hour = this.data.hours[e.detail.value[0]];
    const minute = this.data.minutes[e.detail.value[1]];
    this.setData({
      endTime: [hour, minute]
    });
    console.log('結束時間：', hour + ':' + minute);
  },
  openPopup() {
    this.setData({
      showPopup: true
    });
  },

  closePopup() {
    this.setData({
      showPopup: false
    });
  },
  submitClick() {
    const start_time = wx.getStorageSync('start_time')
    const end_time = wx.getStorageSync('end_time')
    if (!start_time || !end_time) {
      wx.showToast({
        title: '請選擇日期',
        icon: 'none'
      })
      return
    }
    
    // 计算天数差
    const startDate = new Date(start_time.replace(/-/g, '/')) // 兼容 iOS
    const endDate = new Date(end_time.replace(/-/g, '/'))
    const diffTime = endDate.getTime() - startDate.getTime()
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1 // +1 表示包含起始当天
    console.log(`選擇的天數差: ${diffDays} 天`)
    const days = Array.from({
      length: diffDays
    }, (_, i) => `DAY ${i + 1}`)
    const newList = this.data.cardList.map(item => ({
      ...item,
      selected: false
    }))
    wx.removeStorageSync('payload')
    this.setData({
      'itineraryPayload.start_time': start_time,
      'itineraryPayload.end_time': end_time,
      'itineraryPayload.number_day': diffDays,
      days,
      'itineraryPayload.list_item':[],
      cardList: newList,
      allChildren:[],
      showPopup: false,
      diffDays,
    });
  },
  stopTap() {
    // 阻止冒泡，點擊內容區域不關閉彈窗
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  onDayPickerChange(e) {
    console.log(e.detail.value[0]);
    this.setData({
      selectedDayIndex: e.detail.value[0]
    });
  },
  onDayPickerChange2(e) {
    console.log(e.detail.value[0]);
    this.setData({
      daysIndex: e.detail.value[0]
    });
  },
  goPlayClick() {
    const start_time = wx.getStorageSync('start_time')
    const end_time = wx.getStorageSync('end_time')
    if (!start_time || !end_time) {
      wx.showToast({
        title: '請選擇日期',
        icon: 'none'
      })
      return
    }
    wx.setStorageSync('payload', this.data.itineraryPayload)
    wx.navigateTo({
      url: `/pages/Itinerary/addItinerarySelect/addItinerarySelect?diffDays=${this.data.diffDays}`,
    })
  },
  async goPlanClick() {
    const { itineraryPayload,allChildren,days } = this.data
    if (Array.isArray(days) && itineraryPayload.list_item) {
      // 把 days 转换成 [1, 2, 3 ...]
      const dayNums = days.map(d => parseInt(d.replace("DAY ", ""), 10));
    
      // 取出行程里已有的 day_num
      const existing = itineraryPayload.list_item.map(item => item.day_num);
    
      // 找出 days 中缺失的 day
      const missing = dayNums.filter(d => !existing.includes(d));
    
      if (missing.length > 0) {
        missing.forEach(d => {
          wx.showToast({
            title: `請給 DAY ${d} 添加景點`,
            icon: "none"
          });
        });
        return
      }
    }
    if(itineraryPayload.name && allChildren.length>0 && itineraryPayload.itinerary_catalog_id && itineraryPayload.start_time){
      const res = await postItineraryEditForUser(this.data.itineraryPayload)
      if(res.data.ret==1){
        wx.showToast({
          title: '創建成功',
        })
        setTimeout(()=>{
          wx.navigateTo({
            url: `/pages/Itinerary/routeDetailsEdit/routeDetailsEdit?itinerary_id=${res.data.info.itinerary_id}`,
          })
        },500)
      }
    }else{
      wx.showToast({
        title: '請完整填寫行程信息',
        icon:'none'
      })
    }
    
  },

});